import React, { useRef, useState, useEffect } from 'react';
import { View, Text, Image, TouchableOpacity, ViewStyle } from 'react-native';
import { ShortBar, Division } from 'components';
import ModalDropdown from 'react-native-modal-dropdown';
import assets from 'modules/assets';
import * as styles from './style'
import { TextInput, ScrollView } from 'react-native-gesture-handler';
import { themeColors, definedColors, commonStyle, translateSize } from 'styles';
import pos, { PosAppMdmFqOutput, PosAppMdmLd, PosAppMdmDyOutput, PosAppMdmFj } from 'api/pos'
import { getAuthorization, operate } from 'services/authorization';
import Loading from 'components/loading';

type dataType = PosAppMdmFqOutput | PosAppMdmLd | PosAppMdmDyOutput;

const Dropdown: React.FC<{ data: dataType[], defaultValue: dataType, onSelect: (index: string, option: dataType) => void }> = props => {
	const dropdownRef = useRef<dataType>();
	const [selectValue, setSelectValue] = useState<dataType>({})
	useEffect(() => { setSelectValue(props.defaultValue) }, [props.defaultValue])
	return <ModalDropdown<dataType>
		dropdownStyle={{ width: '30%' }}
		dropdownTextStyle={{ fontSize: translateSize(28) }}
		renderRow={(option: dataType, index: string, isSelected: boolean) => <Text style={styles.dropdownRow}>{option.name}</Text>}
		ref={ref => { dropdownRef.current = ref }}
		options={props.data}
		onSelect={(index: string, option: dataType) => {
			setSelectValue(option)
			props.onSelect(index, option)
		}}
	>
		<TouchableOpacity onPress={() => { operate(); dropdownRef.current.show() }}>
			<View style={styles.dropdownContainer}>
				<Text style={styles.dropdownTitle} numberOfLines={1} ellipsizeMode='tail'>{selectValue.name}</Text>
				<Image source={assets.images.icon_arrow_down} style={styles.dropdownIcon} />
			</View>
		</TouchableOpacity>
	</ModalDropdown>
}

export interface RoomInfo {
	planName?: string,
	planId?: string,
	buildingName?: string,
	buildingId?: string,
	unitName?: string,
	unitId?: string,
	roomName?: string,
	roomId?: string
}

interface IProps {
	style?: ViewStyle
	data: PosAppMdmFqOutput[],
	onConfirm: (data: RoomInfo) => void,
	onCancel: () => void
}

const ChooseRoom: React.FC<IProps> = props => {
	const [isLocking, setLocking] = useState(false)
	const [data, setData] = useState<PosAppMdmFqOutput[]>([]);
	const [currentPlanData, setCurrentPlanData] = useState<PosAppMdmFqOutput>({});
	const [currentBuildingData, setCurrentBuildingData] = useState<PosAppMdmLd>({});
	const [unitData, setUnitData] = useState<PosAppMdmDyOutput[]>([]);
	const [currentUnit, setCurrentUnit] = useState<PosAppMdmDyOutput>({});
	const [currentRoom, setCurrentRoom] = useState<PosAppMdmFj>({});
	const [searchList, setSearchList] = useState<PosAppMdmFj[]>([])
	const [searchInput, setSearchInput] = useState('');

	useEffect(() => {
		console.log('111', props.data)
		if (props.data.length > 0) {
			setData(props.data)
			setCurrentPlanData(props.data[0])
		}
	}, [props.data]);

	useEffect(() => {
		if (currentPlanData.ldList && currentPlanData.ldList.length > 0) {
			setCurrentBuildingData(currentPlanData.ldList[0])
		}
	}, [currentPlanData])

	useEffect(() => {
		Loading.show()
		if (currentBuildingData && currentBuildingData.sapId) {
			pos.posApp.getDyList({ sapId: currentBuildingData ?.sapId }).then(res => {
				setUnitData(res || []);
				if (res.length > 0) {
					setCurrentUnit(res[0])
				} else {
					setCurrentUnit([])
				}
			}).finally(() => {
				Loading.hide()
			})
		} else {
			setCurrentUnit([])
			Loading.hide()
		}
	}, [currentBuildingData])

	useEffect(() => {
		setSearchInput('')
		if (currentUnit && currentUnit.fjList) {
			setSearchList(currentUnit.fjList)
		} else {
			setSearchList([])
		}
	}, [currentUnit])


	return <View style={[styles.container, props.style]}>
		<View style={styles.innerContainer}>
			<ShortBar title={getAuthorization().project.name} />
			<View style={styles.itemContainer}>
				<View style={styles.dropdownView}>
					<Dropdown data={data} defaultValue={currentPlanData}
						onSelect={(index: string, option: PosAppMdmFqOutput) => { setCurrentPlanData(option) }} />
				</View>
				<View style={styles.dropdownView}>
					<Dropdown data={currentPlanData.ldList} defaultValue={currentBuildingData}
						onSelect={(index: string, option: PosAppMdmLd) => { setCurrentBuildingData(option) }} />
				</View>
				<TouchableOpacity onPress={() => {
					operate()
					setLocking(!isLocking)
				}}>
					<Text style={[styles.searchBtn, {
						backgroundColor: definedColors.orange
					}]}>{isLocking ? '取消锁定' : '锁定'}</Text>
				</TouchableOpacity>
			</View>
			<View style={styles.itemContainer}>
				<View style={styles.dropdownView}>
					<Dropdown data={unitData} defaultValue={currentUnit}
						onSelect={(index: string, option: PosAppMdmDyOutput) => { setCurrentUnit(option) }} />
				</View>
				<TextInput
					style={styles.input}
					value={searchInput}
					placeholder='请输入房间号'
					onChangeText={text => {
						setSearchInput(text)
					}} />
				<TouchableOpacity onPress={() => {
					operate()
					if (currentUnit && currentUnit.fjList) {
						if (searchInput == '') {
							setSearchList(currentUnit.fjList)
						} else {
							let list: PosAppMdmFj[] = []
							currentUnit.fjList.forEach(item => {
								if (item.name && item.name.indexOf(searchInput) > -1) {
									list.push(item)
								} else if (searchInput.indexOf(item.name) > -1) {
									list.push(item)
								}
							});
							setSearchList(list);
						}
					} else {
						setSearchList([])
					}
				}}>
					<Text style={[styles.searchBtn, {
						backgroundColor: themeColors.primary
					}]}>搜索</Text>
				</TouchableOpacity>
			</View>
			<ScrollView style={{ flex: 1 }}>
				<View style={styles.content}>
					{searchList.map((item, index) => <TouchableOpacity
						key={`${index}`}
						style={styles.contentItem}
						onPress={() => {
							operate()
							setCurrentRoom(item)
						}}>
						<Image style={styles.contentIcon} source={assets.images.icon_room} />
						<Text style={[styles.contentText, { color: currentRoom.zfjnm === item.zfjnm ? themeColors.primary : definedColors.gray66 }]}>{item.name}</Text>
					</TouchableOpacity>)}
				</View>
			</ScrollView>
			<Division />
			<View style={styles.bottomContainer}>
				<TouchableOpacity onPress={() => {
					operate()
					props.onConfirm({
						planName: currentPlanData.name,
						planId: currentPlanData.sapId,
						buildingName: currentBuildingData.name,
						buildingId: currentBuildingData.sapId,
						unitName: currentUnit.name,
						roomName: currentRoom.name,
						roomId: currentRoom.zfjnm
					})
				}}>
					<Text style={styles.comfirm}>确定</Text>
				</TouchableOpacity>
				<TouchableOpacity onPress={() => {
					operate()
					props.onCancel()
				}}>
					<Text style={styles.cancel}>取消</Text>
				</TouchableOpacity>
			</View>
		</View>
	</View>
}

export default ChooseRoom

